package com.banshou.installs.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;

import com.banshou.installs.constant.BaseApplication;
import com.banshou.installs.constant.Config;
import com.banshou.installs.model.dao.PrograssEvent;
import com.banshou.installs.model.dao.ResponseUpdate;
import com.banshou.installs.model.net.ResponseInfo;
import com.banshou.installs.model.net.RetrofitManager;
import com.orhanobut.logger.Logger;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import zlc.season.rxdownload3.RxDownload;
import zlc.season.rxdownload3.core.Status;
import zlc.season.rxdownload3.core.Succeed;

/**
 * Created by cjq on 2018/2/28.
 * Email: stoic_yb@139.com
 * features:
 */

public class UpdateUtil {
    public Context context;

    public UpdateUtil(Context context) {
        this.context = context;
    }

    /**
     * 下载更新
     */
    @SuppressLint("CheckResult")
    public void download(final String url) {
        Logger.d(url);
        RxDownload.INSTANCE.create(url)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(status -> {
                    if (status instanceof Succeed) {
                        install(url);
                    } else {
                        start(url);
                        RxBus.getDefault().post(new PrograssEvent(status));
                    }
                });
    }

    private void start(String url) {
        RxDownload.INSTANCE.start(url).subscribe();
    }

    private void install(String url) {
        RxDownload.INSTANCE.extension(url, IApkInstallExtension.class).subscribe();
    }

    /**
     * 获取当前版本
     */
    public static String getVersionName() {
        PackageManager manager = BaseApplication.getContext().getPackageManager();
        try {
            PackageInfo info = manager.getPackageInfo(BaseApplication.getContext().getPackageName(), 0);
            String versionName = info.versionName;
            return "版本V" + versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return "";
    }
}

